/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package io.renren.modules.oa.redis;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import io.renren.common.utils.DateUtils;
import io.renren.common.utils.RedisUtils;
import io.renren.common.utils.dingtalk.DingtalkUtils;
import io.renren.modules.oa.entity.OaPlanConfigEntity;
import io.renren.modules.oa.entity.OaPlanEmployeeEntity;
import io.renren.modules.oa.entity.OaPlanLogEntity;
import io.renren.modules.oa.entity.UserConfigEntity;
import io.renren.modules.oa.service.OaPlanConfigService;
import io.renren.modules.oa.service.OaPlanEmployeeService;
import io.renren.modules.oa.service.OaPlanLogService;
import io.renren.modules.oa.service.UserConfigService;
import io.renren.modules.oa.websocket.DingtalkSocket;

/**
 * 接口配置工具类
 * 
 * @author Administrator
 *
 */
@Service
public class DingtalkRedis implements ApplicationContextAware {

	private static RedisUtils redisUtils;

	private static UserConfigService userConfigService;

	private static OaPlanEmployeeService oaPlanEmployeeService;

	private static OaPlanConfigService oaPlanConfigService;
	
	private static OaPlanLogService oaPlanLogService;
	
	static{
		 int port = 8899; // 端口
		 DingtalkSocket socket = new DingtalkSocket(port);
		 System.out.println("钉钉广告机(打卡、请假)"+"端口号:"+port);
	     socket.start();
	}
	
	public static List<OaPlanConfigEntity> queryPlanConfigList() {
		String key = "plan_config_list";
		Object result = redisUtils.get(key);
		if (result != null) {
			return (List<OaPlanConfigEntity>)result;
		}else{
			List<OaPlanConfigEntity> planConfigList = oaPlanConfigService.queryPlanConfigList();
			if(planConfigList != null && planConfigList.size() > 0){
				redisUtils.set(key, planConfigList, 3600 * 4);
			}
			return planConfigList;
		}
	}
	
	// 获取用户配置列表
	public static UserConfigEntity getUserConfig(Long merchantId) {
		String key = "user_config_" + merchantId;
		Object result = redisUtils.get(key);
		if (result != null) {
			return (UserConfigEntity)result;
		}else{
			UserConfigEntity userConfig = userConfig = userConfigService.selectByMerchantId(merchantId);
			if (userConfig != null) {
				redisUtils.set(key, userConfig);
			}
			return userConfig;
		}
	}

	// 获取access_token
	public static String getAccessToken(Long merchantId) {
		UserConfigEntity userConfig = getUserConfig(merchantId);
		if (userConfig == null) {
			return null;
		}else{
			return getAccessToken(userConfig.getDingAppkey(), userConfig.getDingAppsecret());
		}
	}

	// 获取access_token
	public static String getAccessToken(String appKey, String appSecret) {
		String key = "dingtalk_access_token_" + appKey;
		Object result = redisUtils.get(key);
		if (result != null) {
			System.out.println("缓存access_token" + result);
			return result.toString();
		}else{
			String token = DingtalkUtils.getAccessToken(appKey, appSecret);
			// {"expires_in":7200,"errmsg":"ok","access_token":"cc3a672628383d4499e36ce9aac5f607","errcode":0}
			JSONObject json = new JSONObject(token);
			if (json.has("errcode") && json.getLong("errcode") == 0L) {
				String access_token = json.getString("access_token");
				System.out.println("新生成access_token" + access_token);
				redisUtils.set(key, access_token, 7000L);
				return access_token;
			} else {
				System.out.println(json.getString("errmsg"));
				return null;
			}
		}
	}

	// 获取部门下的所有员工userId
	public static JSONArray getDeptMember(String accessToken, String deptId) {
		String result = DingtalkUtils.getDeptMember(accessToken, deptId);
		// System.out.println(result);
		// {"userIds":["192616591829793791","04131240368472","15326641551086850","085162157362","152608142236526592","172936334126639687","manager847","1202180815765191","193436415221650092","015322631397","036536453924158093","2427521824590785","025837613587"],"errmsg":"ok","errcode":0}
		JSONObject json = new JSONObject(result);
		if (json.has("errcode") && json.getLong("errcode") == 0L) {
			JSONArray userIds = json.getJSONArray("userIds");
			System.out.println("查询所有员工userIds:" + userIds);
			return userIds;
		} else {
			System.out.println(json.getString("errmsg"));
			return null;
		}
	}

	// 获取员工详情
	public static JSONObject getMember(String accessToken, String userid) {
		String result = DingtalkUtils.getMember(accessToken, userid);
		// System.out.println(result);
		// {"orderInDepts":"{1:176390142827977512}","position":"UI","department":[1],"unionid":"mMXHB4AQg9xrSriPBj3FmXQiEiE","tel":"839","userid":"192616591829793791","isSenior":false,"dingId":"$:LWCP_v1:$9KJagOnpHUPRCDz8gDzAow==","isBoss":false,"name":"白亚东","errmsg":"ok","stateCode":"86","avatar":"https://static.dingtalk.com/media/lADPBbCc1j7zxpXNAtbNAug_744_726.jpg","errcode":0,"isLeaderInDepts":"{1:false}","active":true,"isAdmin":false,"openId":"mMXHB4AQg9xrSriPBj3FmXQiEiE","mobile":"17331977837","isHide":false}
		JSONObject json = new JSONObject(result);
		if (json.has("errcode") && json.getLong("errcode") == 0L) {
			return json;
		} else {
			System.out.println(result);
			return null;
		}
	}
	
	// 获取部门下的所有员工userId
	public static JSONArray attendanceList(String accessToken, List<String> userids) {
		String result = DingtalkUtils.attendanceList(accessToken , userids);
		System.out.println(result);
		// System.out.println(result);
		// {"hasMore":false,"errmsg":"ok","recordresult":[{"recordId":10352252590,"sourceType":"AUTO_CHECK","workDate":1540742400000,"locationResult":"Normal","planId":29495448963,"baseCheckTime":1540773300000,"id":22045831790,"groupId":20335662,"userCheckTime":1540772735000,"userId":"192616591829793791","checkType":"OnDuty","timeResult":"Normal","corpId":"ding278cea6787cd42ec"},{"recordId":10332006069,"sourceType":"USER","workDate":1540742400000,"locationResult":"Normal","planId":29495448964,"baseCheckTime":1540785600000,"id":22172579419,"groupId":20335662,"userCheckTime":1540785712000,"userId":"192616591829793791","checkType":"OffDuty","timeResult":"Normal","corpId":"ding278cea6787cd42ec"},{"recordId":10333389432,"sourceType":"AUTO_CHECK","workDate":1540742400000,"locationResult":"Normal","planId":29495448965,"baseCheckTime":1540791300000,"id":22179195187,"groupId":20335662,"userCheckTime":1540789733000,"userId":"192616591829793791","checkType":"OnDuty","timeResult":"Normal","corpId":"ding278cea6787cd42ec"}],"errcode":0}
		JSONObject json = new JSONObject(result);
		if (json.has("errcode") && json.getLong("errcode") == 0L) {
			JSONArray recordresult = json.getJSONArray("recordresult");
			System.out.println("打卡记录:" + recordresult);
			return recordresult;
		} else {
			System.out.println(json.getString("errmsg"));
			return null;
		}
	}

	// 获取值班员工列表
	public static List<OaPlanEmployeeEntity> queryAllList(Long merchantId) {
		String key = "employee_list_" + merchantId;
		Object result = redisUtils.get(key);
		if (result != null) {
			return (List<OaPlanEmployeeEntity>)result;
		}else{
			List<OaPlanEmployeeEntity> list = oaPlanEmployeeService.queryAllList(merchantId);
			if (list != null && list.size() > 0) {
				redisUtils.set(key, list);
			}
			return list;
		}
	}
	
	// 获取值班员工列表
	public static List<OaPlanEmployeeEntity> queryActiveList(Long merchantId) {
		String key = "employee_active_list_" + merchantId;
		Object result = redisUtils.get(key);
		if (result != null) {
			return (List<OaPlanEmployeeEntity>)result;
		}else{
			List<OaPlanEmployeeEntity> list = oaPlanEmployeeService.queryActiveList(merchantId);
			if (list != null && list.size() > 0) {
				redisUtils.set(key, list);
			}
			return list;
		}
	}

	/**
	 * 获取值班配置
	 * 
	 * @param merchantId
	 * @return
	 */
	public static OaPlanConfigEntity getPlanConfig(Long merchantId) {
		String key = "plan_config_" + merchantId;
		Object result = redisUtils.get(key);
		if (result != null) {
			return (OaPlanConfigEntity)result;
		}else{
			OaPlanConfigEntity config = oaPlanConfigService.selectByMerchantId(merchantId);
			if (config != null) {
				redisUtils.set(key, config);
			}
			return config;
		}
	}

	

	
	public static void delPlanConfigList() {
		String key = "plan_config_list";
		redisUtils.del(key);
	}
	// 删除值班配置
	public static void delPlanConfig(Long merchantId) {
		String key = "plan_config_" + merchantId;
		redisUtils.del(key);
	}

	// 删除员工列表
	public static void delEmployeeList(Long merchantId) {
		String key = "employee_list_" + merchantId;
		redisUtils.del(key);
	}
	public static void delActiveList(Long merchantId) {
		String key = "employee_active_list_" + merchantId;
		redisUtils.del(key);
	}

	// 删除钉钉缓存
	public static void delAccessToken(Long merchantId) {
		String key = "user_config_" + merchantId;
		redisUtils.del(key);
		UserConfigEntity userConfig = userConfigService.selectByMerchantId(merchantId);
		if (userConfig != null && StringUtils.isNotEmpty(userConfig.getDingAppkey())) {
			key = "dingtalk_access_token_" + userConfig.getDingAppkey();
			redisUtils.del(key);
		}
	}
	
	/**
	 * 判读用户是否打卡
	 * @param merchantId
	 * @return
	 */
	public static boolean isActive(String userid) {
		String key = "userid_"+ DateUtils.format(new Date()) + "_" + userid;
		return redisUtils.hasKey(key);
	}
	
	/**
	 * 已打卡
	 * @param userid
	 * @return
	 */
	public static void setActive(String userid,String value) {
		String key = "userid_"+ DateUtils.format(new Date()) + "_" + userid;
		redisUtils.set(key, value);
	}
	

	
	public static String getAdInfo(Long merchantId){
		/*String key = "ad_info_" + merchantId;
		Object adinfo = redisUtils.get(key);
		if (adinfo != null) {
			return adinfo.toString();
		}else{
			OaPlanConfigEntity planConfig = DingtalkRedis.getPlanConfig(merchantId);
			List<OaPlanLogEntity> list = DingtalkRedis.queryPlanLogList();
			
			JSONArray daka_list = new JSONArray();
			String qingjia = "请假：";
			JSONObject result = new JSONObject();
			result.put("code", 0);
			result.put("title", planConfig.getTitle());
			
		
			for (OaPlanLogEntity oaPlanLogEntity : list) {
				JSONObject child = new JSONObject();
				child.put("name", oaPlanLogEntity.getName());
				child.put("avatar", oaPlanLogEntity.getAvatar()  != null ? oaPlanLogEntity.getAvatar() : "https://static.dingtalk.com/media/lADPDgQ9qUPY6M3NAlzNAlw_604_604.jpg");
				child.put("isAvatar", oaPlanLogEntity.getAvatar() != null ? true : false);
				if(oaPlanLogEntity.getType().equals("1")){   //打卡
					daka_list.put(child);
				}else if(oaPlanLogEntity.getType().equals("2")){   //请假
					qingjia += oaPlanLogEntity.getName() + "&nbsp;&nbsp;";
				}
			}
			result.put("daka_count", daka_list.length());
			result.put("daka_list", daka_list);
			result.put("qingjia", qingjia);
			redisUtils.set(key, result.toString(), 10);
			return result.toString();
		}*/
		
		OaPlanConfigEntity planConfig = oaPlanConfigService.selectByMerchantId(merchantId);
		List<OaPlanLogEntity> list = oaPlanLogService.selectList("1",DateUtils.getStartTime(), DateUtils.getEndTime());
		
		JSONArray daka_list = new JSONArray();
		String qingjia = "";
		JSONObject result = new JSONObject();
		result.put("code", 0);
		result.put("title", planConfig.getTitle());
		
	
		for (OaPlanLogEntity oaPlanLogEntity : list) {
			JSONObject child = new JSONObject();
			child.put("name", oaPlanLogEntity.getName());
			child.put("avatar", oaPlanLogEntity.getAvatar()  != null ? oaPlanLogEntity.getAvatar() : "https://static.dingtalk.com/media/lADPDgQ9qUPY6M3NAlzNAlw_604_604.jpg");
			child.put("isAvatar", oaPlanLogEntity.getAvatar() != null ? true : false);
			if(oaPlanLogEntity.getType().equals("1")){   //打卡
				daka_list.put(child);
			}
		}
		list = oaPlanLogService.selectList("2",DateUtils.getStartTime(), DateUtils.getEndTime());
		for (OaPlanLogEntity oaPlanLogEntity : list) {
			if(oaPlanLogEntity.getType().equals("2")){   //请假
				qingjia += oaPlanLogEntity.getName() + "&nbsp;&nbsp;";
			}
		}
		if(StringUtils.isNotEmpty(qingjia)){
			qingjia = "请假：" + qingjia;
		}
		result.put("daka_count", daka_list.length());
		result.put("daka_list", daka_list);
		result.put("qingjia", qingjia );
		result.put("zhiri", planConfig.getPlanJson());
		
		//redisUtils.set(key, result.toString(), 10);
		return result.toString();
		
	}


	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		redisUtils = (RedisUtils) applicationContext.getBean("redisUtils");
		userConfigService = (UserConfigService) applicationContext.getBean("userConfigService");
		oaPlanEmployeeService = (OaPlanEmployeeService) applicationContext.getBean("oaPlanEmployeeService");
		oaPlanConfigService = (OaPlanConfigService) applicationContext.getBean("oaPlanConfigService");
		oaPlanLogService = (OaPlanLogService) applicationContext.getBean("oaPlanLogService");
		

	}
}
